import time
import network
from umqttsimple import MQTTClient
import machine

def do_connect():
    """
    作用：连接WiFi网络
    """
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        # 网络未连接
        wlan.connect('V40','123qiu456')
        i = 1
        while not wlan.isconnected():
            print(f"正在连接wifi...{i}s")
            time.sleep(1)
            i+=1
    print('已连接上网络，IP为:',wlan.ifconfig()[0])
    
def sub_cb(topic, msg): # 设置回调函数，收到服务器消息后调用
    print("收到来自'{}'主题的消息，消息内容为'{}'。".format(topic.decode(),msg.decode()))
    if msg.decode() == "LED_ON":
        led.value(1)
    elif msg.decode() == "LED_OFF":
        led.value(0)
    else:
        led.value(1)
        time.sleep_ms(10)
        led.value(0)

# 1. 联网
do_connect()

# 初始化led灯
led = machine.Pin(2,machine.Pin.OUT)

# 2.创建mqtt
client = MQTTClient("esp32mqtt","192.168.16.220")
client.set_callback(sub_cb)
client.connect() # 建立连接 
client.subscribe(b"mqtt_esp32_project_01") # 订阅"test"主题

while True:
    client.check_msg()
    time.sleep(1)

